package com.liao.order.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.liao.common.constant.SessionEnum;
import com.liao.common.dto.OrderSaveParame;
import com.liao.common.dto.Skus;
import com.liao.common.entity.member.UserAddressEntity;
import com.liao.common.entity.member.UserEntity;
import com.liao.common.entity.order.OrderItemEntity;
import com.liao.common.entity.order.OrdersEntity;
import com.liao.common.entity.product.SkuEntity;
import com.liao.common.utils.PageUtils;
import com.liao.common.utils.Result;
import com.liao.common.vo.order.OrderPreVo;
import com.liao.common.vo.order.OrderSaveReq;
import com.liao.order.feign.MemberFeignService;
import com.liao.order.feign.ProductFeignService;
import com.liao.order.service.OrdersService;
import com.liao.order.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

import static com.liao.common.constant.order.OrderEnum.ORDER_LOCK_KEY;
import static com.liao.common.constant.order.OrderEnum.ORDER_STATUS_NOPAYMENT;


/**
 * 订单主表
 *
 * @author liao
 * @email 2858015963@qq.com
 * @date 2025-03-14 09:23:11
 */

@Slf4j
@RestController
@RequestMapping("order/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ProductFeignService productFeignService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public PageUtils<OrdersEntity> list(@RequestParam Map<String, Object> params) {
        return ordersService.queryPage(params);

    }


    /**
     * 信息
     */
    @RequestMapping("/info/{orderId}")
    public OrdersEntity info(@PathVariable("orderId") String orderId) {
        return ordersService.getById(orderId);

    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public void save(@RequestBody OrdersEntity orders) {
        ordersService.save(orders);

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public void update(@RequestBody OrdersEntity orders) {
        ordersService.updateById(orders);

    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public void delete(@RequestBody String[] orderIds) {
        ordersService.removeByIds(Arrays.asList(orderIds));

    }


    /**
     * 提交订单（未支付）
     */
    @Transactional
    @PostMapping("/add")
    public void add(@RequestBody OrderSaveParame orderSaveParame) {
//获取请求保存订单参数
        System.out.println(orderSaveParame);

        //获取地址信息
        Result<UserAddressEntity> userAddressEntityResult = memberFeignService.addressInfo(orderSaveParame.getAddressId());
        UserAddressEntity userAddressEntity = userAddressEntityResult.getData();


//封装保存订单所需要的数据
        OrderSaveReq orderSaveReq = new OrderSaveReq();
        OrdersEntity orders = new OrdersEntity();
        ArrayList<OrderItemEntity> orderItems = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);

        //获取sku信息
        for (Skus sku : orderSaveParame.getSkus()) {
            Result<SkuEntity> skuEntityResult = productFeignService.getSkuinfo(String.valueOf(sku.getSkuId()));
            SkuEntity data = skuEntityResult.getData();

            OrderItemEntity item = new OrderItemEntity();
            item.setSkuId(sku.getSkuId());
            item.setQuantity(sku.getCount());
            item.setPrice(data.getPrice());
            item.setAttributes(data.getAttributes());
            item.setTotalmoney(data.getPrice().multiply(new BigDecimal(sku.getCount())));
            totalAmount = totalAmount.add(data.getPrice().multiply(new BigDecimal(sku.getCount())));
            orderItems.add(item);
        }


//        StpUtil.checkRoleOr("admin", "user");
        UserEntity user = (UserEntity) StpUtil.getSession().get(SessionEnum.USER_INFO_KEY);
        orders.setMemberId(user.getUserId());
        orders.setName(user.getUsername());
        orders.setTotalAmount(totalAmount);
        orders.setOrderStatus(ORDER_STATUS_NOPAYMENT);
//        设置为未支付状态
        orders.setPaymentStatus(1);
        BeanUtils.copyProperties(userAddressEntity, orders);
        orders.setPayMoney(totalAmount);
        orders.setCreatedAt(null);
        orderSaveReq.setOrder(orders);
        orderSaveReq.setOrderItemList(orderItems);


        int hashKey = orderSaveReq.hashCode();//获取token


        String key = ORDER_LOCK_KEY + hashKey;
        //获取锁
        Boolean isLock = redisUtils.setIfAbsent(key, hashKey, 60);

        if (!isLock) {//未获取到锁 说明订单重复提交 返回错误信息
//            return R.error("订单重复提交");
            throw new RuntimeException("订单重复提交");
        }

        try {
            log.info("--------------获取锁成功，生成订单------------------");
            ordersService.add(orderSaveReq);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (key.equals(redisUtils.get(key))) {
                log.info("--------------释放锁------------------");
                redisUtils.delete(key);
            }
        }
    }


    /**
     * 获取订单详情
     */
    @GetMapping("/status/{orderId}")
    public OrdersEntity getOrderByOrderId(@PathVariable("orderId") String orderId) {
        return ordersService.getOrderByOrderId(orderId);
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @return
     */
    @PostMapping("/cancel")
    public void cancelOrder(@RequestBody String orderId) {
        ordersService.closeOrder(ordersService.getById(orderId));

    }

    /**
     * 支付订单
     */
    @PostMapping("/payment")
    public void payOrder(@RequestBody String orderId) {
        ordersService.payOrder(orderId);
    }

    /**
     * 获取购物车订单信息
     */
    @GetMapping("/getCartOrder")
    public OrderPreVo getCartOrder() {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("请先登录");
        }
        OrderPreVo cartOrder = ordersService.getCartOrder();
        return cartOrder;
    }
}
